<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/8/11
 * Time: 13:41
 */
namespace app\command;

use app\api\model\Inventory;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Log;

class ImportJstOrder extends Command
{
    protected $sourceMap = [
        'Shopify' => 2, '聚水潭' => 3, '速卖通' => 4,
        '淘宝/天猫' => 5, '闲鱼' => 6, 'Yandex' => 7, 'Ozone' => 8, 'Shopee' => 9, 'Shopee' => 9, 'LAZADA' => 10,
        'Tiktok' =>11, 'Newegg' => 12, 'Amazon' => 13,'Ebay' => 13
    ];
    protected function configure()
    {
        $this->setName('order:importJstOrder')
            ->setDescription('导入聚水潭订单数据')
            ->addArgument('file', null, 'Excel文件路径', true);
    }
    protected function checkFileAccessibility(string $file, Output $output)
    {
        if (!file_exists($file)) {
            $errMsg = "文件不存在: {$file}";
            $output->writeln("<error>{$errMsg}</error>");
            Log::error($errMsg);
            throw new \Exception($errMsg);
        }

        if (!is_readable($file)) {
            $errMsg = "文件不可读: {$file}";
            $output->writeln("<error>{$errMsg}</error>");
            Log::error($errMsg);
            throw new \Exception($errMsg);
        }

        $ext = pathinfo($file, PATHINFO_EXTENSION);
        if (!in_array(strtolower($ext), ['xlsx', 'xls'])) {
            $errMsg = "文件类型错误: {$ext}，仅支持.xlsx或.xls";
            $output->writeln("<error>{$errMsg}</error>");
            Log::error($errMsg);
            throw new \Exception($errMsg);
        }

        $fileSize = round(filesize($file) / 1048576, 2);
        $output->writeln("[DEBUG] 文件验证通过: 大小={$fileSize}MB");
        Log::info(" [jst] 文件验证通过: 大小={$fileSize}MB");
    }
    protected function execute(Input $input, Output $output)
    {
        // 解除脚本限制
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln("[INFO] 已解除脚本执行时间和内存限制");
        $output->writeln("<======================        开始处理文件          ===================>");
        Log::info(" [jst] 脚本启动，已解除时间和内存限制");
        Log::info(" [jst] <======================        开始处理文件          ===================>");
        $file = $input->getArgument('file');

        // 标准化路径处理（解决Windows路径问题）
        $file = str_replace('\\', '/', $file);
        $file = realpath($file) ?: $file;

        $output->writeln("开始处理文件: {$file}");
        Log::info(" [jst] 开始处理文件: {$file}");

        // 检查文件是否存在和可读
        $this->checkFileAccessibility($file, $output);
        $startTime = microtime(true);
        $output->writeln("[DEBUG] 正在加载Excel文件...");
        Log::info(" [jst] 正在加载Excel文件: {$file}");

        try {
            // 详细文件信息记录
            $fileSize = round(filesize($file) / 1048576, 2);
            $output->writeln("[DEBUG] 文件大小: {$fileSize}MB");
            Log::info(" [jst] 文件大小: {$fileSize}MB");

            // 高效加载Excel文件（只读数据）
            $reader = IOFactory::createReaderForFile($file);
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($file);
        } catch (Exception $e) {
            throw new \Exception("Excel文件加载失败: " . $e->getMessage());
        } catch (\Throwable $e) {
            throw new \Exception("文件加载错误: " . $e->getMessage());
        }

        $memUsage = round(memory_get_usage() / 1048576, 2);
        $output->writeln("[DEBUG] Excel文件加载完成。内存用量: {$memUsage}MB");
        Log::info(" [jst] Excel文件加载完成，内存用量: {$memUsage}MB");
        $sheet = $spreadsheet->getSheetByName('Sheet1'); // 根据实际sheet名调整
        $rows = $sheet->toArray();

        // 获取标题映射
        $headers = array_shift($rows);
        $mapping = $this->createColumnMapping($headers);

        // 按内部订单号分组
        $groupedOrders = [];
        foreach ($rows as $row) {
            $orderSn = $row[$mapping['内部订单号']];
            $groupedOrders[$orderSn][] = $row;
        }

        // 处理每个订单
        foreach ($groupedOrders as $internalSn => $items) {
            $this->processOrder($internalSn, $items, $mapping, $output);
        }

        $output->writeln('导入完成！');
    }

    private function createColumnMapping($headers)
    {
        // 列名映射（根据实际Excel列名调整）
        return [
            '内部订单号'  => array_search('内部订单号', $headers),
            '线上订单号'  => array_search('线上订单号', $headers),
            '订单状态'    => array_search('订单状态', $headers),
            '买家账号'    => array_search('买家账号', $headers),
            '买家邮箱'    => array_search('买家邮箱', $headers), // 根据实际列名调整
            '订单日期'    => array_search('订单日期', $headers),
            '付款日期'    => array_search('付款日期', $headers),
            '收货人'     => array_search('收货人', $headers),
            '省'     => array_search('省', $headers),
            '市'     => array_search('市', $headers),
            '区县'     => array_search('区县', $headers),
            '商品编码'    => array_search('商品编码', $headers),
            '商品简称'    => array_search('商品简称', $headers),
            '销售数量'    => array_search('销售数量', $headers),
            '已付金额'    => array_search('已付金额', $headers),
            '应付金额'    => array_search('应付金额', $headers),
            '运费收入分摊' => array_search('运费收入分摊', $headers),
            '订单重量'    => array_search('订单重量', $headers),
            '业务员'     => array_search('业务员', $headers),
            '币种'       => array_search('币种', $headers),
            '买家留言'       => array_search('买家留言', $headers),
            '卖家备注'       => array_search('卖家备注', $headers),
            '汇率'       => array_search('汇率', $headers),
            '仓库'       => array_search('新系统仓库', $headers),
            'sku'       => array_search('新系统商品sku', $headers),
            '物流批次'       => array_search('物流批次', $headers),
            '售价'       => array_search('售价', $headers), // 根据实际列名调整
            '收件国家'       => array_search('收件国家', $headers), // 根据实际列名调整
            '收件地址'       => array_search('收件地址', $headers), // 根据实际列名调整
            '商店站点'       => array_search('商店站点', $headers) // 根据实际列名调整
        ];
    }

    private function processOrder($internalSn, $items, $mapping, $output)
    {
        // 记录开始处理订单
        $output->writeln("开始处理订单: {$internalSn}");
        Log::info(" [jst] 开始处理订单".json_encode(['internalSn' => $internalSn, 'items_count' => count($items)]));

        try {

            // 基础数据提取
            $firstItem = $items[0];
            Db::name('order_item')->where('order_id',$firstItem[$mapping['内部订单号']])->delete();



            $excelStatus = $firstItem[$mapping['订单状态']];
            $output->writeln("提取基础数据: 状态={$excelStatus}");
            Log::info(" [jst] 基础数据提取完成".json_encode(['excelStatus' => $excelStatus]));

            // 1. 订单状态处理
            if ($excelStatus == '已取消') {
                $output->writeln("已取消订单，跳过处理");
                Log::info(" [jst] 跳过取消订单".json_encode( ['internalSn' => $internalSn]));
                return;
            }

            list($status, $payStatus) = $this->mapOrderStatus(
                $excelStatus,
                (float)$firstItem[$mapping['应付金额']],
                (float)$firstItem[$mapping['已付金额']]
            );
            $country = $this->getLocalCountry(
                $firstItem[$mapping['收件国家']]
            );
            $output->writeln("状态映射结果: status={$status}, payStatus={$payStatus}");
            Log::info(" [jst] 订单状态映射完成".json_encode( ['status' => $status, 'payStatus' => $payStatus]));
            $source = $this->mapSource($firstItem[$mapping['商店站点']]?? '');
            // 2. 线上订单号处理
            $orderNo = $this->processOrderNo(
                $firstItem[$mapping['线上订单号']]
            );
            $output->writeln("线上订单号处理: {$orderNo}");
            Log::info(" [jst] 线上订单号处理完成".json_encode( ['orderNo' => $orderNo]));

            // 3. 买家账号处理
            $userId = $this->getOrCreateCustomer(
                $firstItem[$mapping['买家账号']],
                $firstItem[$mapping['买家邮箱']] ?? null
            );
            $output->writeln("客户处理完成: userID={$userId}");
            Log::info(" [jst] 客户处理完成".json_encode( ['userId' => $userId]));

            // 4. 业务员映射
            $ownerId = $this->getStaffId(
                $firstItem[$mapping['业务员']]
            );
            $output->writeln("业务员映射: ownerID={$ownerId}");
            Log::info(" [jst] 业务员映射完成".json_encode(['ownerId' => $ownerId]));

            // 5. 币种处理
            list($currencyId, $currencyRate) = $this->processCurrency(
                $firstItem[$mapping['币种']] ?? 'CNY',
                (float)($firstItem[$mapping['汇率']] ?? 1)
            );
            $output->writeln("币种处理: currencyID={$currencyId}, rate={$currencyRate}");
            Log::info(" [jst] 币种处理完成".json_encode(['currencyId' => $currencyId, 'rate' => $currencyRate]));

            // 6. 运费计算（多行相加）
            $logisticsFee = array_sum(array_column($items, $mapping['运费收入分摊']));
            $output->writeln("运费计算: fee={$logisticsFee}");
            Log::info(" [jst] 运费计算完成".json_encode( ['fee' => $logisticsFee]));

            $order_num =  array_sum(array_column($items, $mapping['销售数量']));

            // 构建订单主数据
            $orderData = [
                'id'   => $firstItem[$mapping['内部订单号']],
                'order_no'   => $orderNo,
                'user_id'    => $userId,
                'status'     => $status,
                'pay_status' => $payStatus,
                'order_num' => $order_num,
                'address' => implode(' ',[$firstItem[$mapping['省']],$firstItem[$mapping['市']],$firstItem[$mapping['区县']]]),
                'total_amount' => $this->convertCurrency(
                    $currencyId,
                    (float)$firstItem[$mapping['应付金额']],
                    $currencyRate
                ),
                'pay_amount' => $this->convertCurrency(
                    $currencyId,
                    (float)$firstItem[$mapping['已付金额']],
                    $currencyRate
                ),
                'logistics_fee' => $this->convertCurrency(
                    $currencyId,
                    $logisticsFee,
                    $currencyRate
                ),
                'product_total_amount' => $this->convertCurrency(
                    $currencyId,
                    $firstItem[$mapping['应付金额']]-$logisticsFee,
                    $currencyRate
                ),
                'product_total_original_amount' => $this->convertCurrency(
                    $currencyId,
                    $firstItem[$mapping['应付金额']]-$logisticsFee,
                    $currencyRate
                ),
                'order_weight' => (float)$firstItem[$mapping['订单重量']],
                'create_time' => date('Y-m-d H:i:s', $this->excelTimeToUnix($firstItem[$mapping['订单日期']])),
                'pay_time' => date('Y-m-d H:i:s',$this->excelTimeToUnix($firstItem[$mapping['付款日期']])),
                'signing_date' => date('Y-m-d',$this->excelTimeToUnix($firstItem[$mapping['订单日期']])),
                'source'      => $source, // 聚水潭
                'order_type'      => 1, // 聚水潭
                'delivery_method'      => 1, // 聚水潭
                'owner'       => $ownerId,
                'currency'    => $currencyId == 214? 214:4,
                'first_name'  => '',
                'last_name'   => trim($firstItem[$mapping['收货人']]),
                'email'       => $firstItem[$mapping['买家邮箱']] ?? null,
                'address'       => $firstItem[$mapping['收件地址']] ?? null,
                'country_name'       => $firstItem[$mapping['收件国家']] ?? null,
                'country_id'       => $country,
                'notes'       => $firstItem[$mapping['买家留言']] ?? null,
                'order_remark'       => $firstItem[$mapping['卖家备注']] ?? null,
            ];
            $output->writeln("订单主数据构建完成");
            Log::info(" [jst] 订单主数据构建完成".json_encode( ['orderData' => $orderData]));

            // 1. 获取本地订单
            $localOrder = Db::name('order')->where('id', $orderData['id'])->where('is_del',0)->find();
            // 数据库事务开始
            $output->writeln("启动数据库事务");
            Log::info(" [jst] 启动数据库事务");
            Db::startTrans();
            if($localOrder){
                $output->writeln("发现已存在订单: ID={$orderData['id']}");
                Log::info(" [jst] 发现已存在订单".json_encode(['orderId' => $orderData['id']]));
                $orderId = $orderData['id'];
                $orderData = array_merge($orderData,[
                    'review_node' => null,
                    'exceptionstatus' => null,
                ]);
                #处理库存
                if(($localOrder['status'] == 10 && $localOrder['pay_status'] == 4) ||
                    ($localOrder['status'] == 30 && $localOrder['pay_status'] == 3)){

                    $output->writeln("执行库存解锁操作");
                    Log::info(" [jst] 开始解锁库存".json_encode(['orderId' => $orderData['id']]));
                    if($localOrder['review_node'] != 1) {
                        $this->unlockInventory($localOrder);
                    }
                    $output->writeln("更新主订单数据");
                    Db::name('order')->where('id',$orderData['id'])->update($orderData);

                } else {
                    $output->writeln("直接更新订单数据");
                    Db::name('order')->where('id',$orderData['id'])->update($orderData);
                }
            } else {
                $output->writeln("插入新订单数据");
                Log::info(" [jst] 插入新订单".json_encode( ['orderNo' => $orderNo]));
                $orderId = Db::name('order')->insertGetId($orderData);
            }

            // 处理订单明细
            $output->writeln("开始处理{$orderId}的订单明细，共".count($items)."条");
            Log::info(" [jst] 开始处理订单明细".json_encode(['orderId' => $orderId, 'itemCount' => count($items)]));
            $iterms = [];
            $exceptionstatus = [];
            foreach ($items as $index => $item) {
                $output->writeln("处理明细#{$index}: 商品ID=".$item[$mapping['商品编码']]);
                $iterms[] = $this->processOrderItem($orderId, $item, $mapping, $currencyRate,$currencyId, $userId,$status);
            }
            if($iterms){
                foreach ($iterms as $iterm){
                    if(empty($exceptionstatus) && $iterm['exceptionstatus'] == 3){
                        $exceptionstatus = [
                            'review_node' => 1,
                            'exceptionstatus' => 3,
                        ];
                    }
                }

            }
            Db::name('order_item')->insertAll($iterms);
            if(!empty($exceptionstatus)  && $status != 100){
                Db::name('order')->where('id',$orderId)->update($exceptionstatus);
            }
            $output->writeln("订单明细处理完成");
            Log::info(" [jst] 订单明细处理完成".json_encode( ['orderId' => $orderId]));
            #锁定库存
            $orderInfo = \app\api\model\Order::where('id',$orderId)->find();
            if($orderInfo->review_node != 1){
                if(($orderInfo->status == 10 && $orderInfo->pay_status == 4) ||
                    ($orderInfo->status == 30 && $orderInfo->pay_status == 3)) {

                    $output->writeln("开始锁定库存");
                    Log::info(" [jst] 库存锁定开始".json_encode(['orderId' => $orderId]));

                    $res = (new \app\common\service\Inventory())->lockInventory(['id' => $orderId]);
                    $output->writeln("库存锁定结果: ".($res ? '成功' : '失败'));
                    Log::info(" [jst] 库存锁定结果".json_encode( ['result' => $res, 'orderId' => $orderId]));

                    if (!$res) {
                        $output->writeln("处理库存锁定失败");
                        Log::error(" [jst]  库存锁定失败".json_encode( ['orderId' => $orderId]));
                        $this->updateOrderAfterLockInventoryFail($orderId);
                    }
                }
            }
            // 提交事务
            Db::commit();

            $output->writeln("订单 {$internalSn} 导入成功");
            Log::info(" [jst] 订单导入成功".json_encode(['internalSn' => $internalSn, 'orderId' => $orderId]));

        } catch (\Exception $e) {
            // 获取详细错误信息
            $errorMsg = sprintf(
                "文件: %s\n行号: %d\n错误: %s\n堆栈: %s",
                $e->getFile(),
                $e->getLine(),
                $e->getMessage(),
                $e->getTraceAsString()
            );

            // 回滚事务并记录错误
            Db::rollback();
            $output->writeln("订单 {$internalSn} 导入失败: ".$e->getMessage());
            Log::error(" [jst]  订单导入失败".json_encode( [
                'internalSn' => $internalSn,
                'error' => $errorMsg,
                'trace' => $e->getTrace()
            ]));
        }
    }

    private function mapOrderStatus($excelStatus, $totalAmount, $payAmount)
    {
        // 1. 已发货/发货中订单处理（状态100 + 支付状态3）
        if ($excelStatus == '已发货' || $excelStatus == '发货中(打单拣货)') {
            return [100, 3]; // status=100, pay_status=3
        }

        // 2. 已取消订单跳过（不处理）
        if ($excelStatus == '已取消') {
            return [null, null]; // 返回特殊值，外层调用需跳过
        }

        // 3. 其他状态（已付款待审核/异常）的金额逻辑判断
        // 使用bcmath精确比较金额（避免浮点数精度问题）
        $totalAmount = (string)$totalAmount;
        $payAmount = (string)$payAmount;

        // 应付金额 <= 已付金额 → 待发货(30) + 已支付(3)
        if (bccomp($totalAmount, $payAmount, 2) <= 0) {
            return [30, 3];
        }
        // 应付金额 > 已付金额 且 已付金额 > 0 → 待支付(10) + 部分支付(4)
        elseif (bccomp($payAmount, '0', 2) > 0) {
            return [10, 4];
        }

        // 默认返回待支付（兜底逻辑）
        return [10, 1]; // 待支付 + 未支付
    }
    private function unlockInventory($localOrder)
    {
        if ($localOrder['review_node'] != 1) {

            $items = \app\api\model\OrderItem::where('order_id', $localOrder['id'])->select()->toArray();
            if (empty($items)) {
                throw new \Exception('订单商品不存在');
            }
            $condition = [];
            foreach ($items as $item) {
                $condition[] = [
                    'productid' => $item['product_id'],
                    'wid' => $item['warehouse_id'],
                    'arrival_date' => $item['arrival_date'],
                    'is_futures' => $item['is_futures'],
                    'quantity' => $item['quantity']
                ];
            }
            $oProductInventory = new ProductInventory();
            $result = $oProductInventory->inventory($condition);
            $data = $result['data'] ?? [];
            if (!$data || $result['code'] === 1) {
                throw new \Exception('未找到库存数据');
            }
            $inventorySet = [];
            foreach ($data as $value) {
                if ($value['exceptionstatus'] == 1) {
                    throw new \Exception('库存不足');
                }
                foreach ($value['items'] as $val) {
                    $inventorySet[$val['id']] = $val['pay_quantity'];
                }
            }
            // 获取库存信息
            $oInventoryModel = \app\admin\model\Inventory::whereIn('id', array_keys($inventorySet))->select();
            foreach ($oInventoryModel as $inv) {
                // 锁定库存
                $inv->lock_qty = $inv->lock_qty - $inventorySet[$inv->id] ?? 0;
                if (!$inv->save()) {
                    throw new \Exception('库存释放失败');
                }
            }
        }
    }
    #库存锁定失败 更新订单 和订单行状态
    private function updateOrderAfterLockInventoryFail($id)
    {
        #锁定失败 标记异常
        $orderInfo = \app\api\model\Order::where('id',$id)->where('is_del',0)->find();
        if($orderInfo){
            $orderInfo->review_node = 1;
            $orderInfo->exceptionstatus = 1;
            $orderInfo->save();
            \app\api\model\OrderItem::where('order_id', $id)->update(['exceptionstatus'=>1]);
        }
    }
    // 处理线上订单号（逗号分隔处理）
    private function processOrderNo($orderNos)
    {
        if (strpos($orderNos, ',') !== false) {
            $parts = explode(',', $orderNos);
            return trim($parts[0]) . (isset($parts[1]) ? ',' . trim($parts[1]) : '');
        }
        return $orderNos;
    }
    private function mapSource($value): int
    {
        $mapped = $this->sourceMap[$value] ?? 0;
        Log::info(" 来源映射: {$value} => {$mapped}");
        return $mapped;
    }
    // 客户查询/创建
    private function getOrCreateCustomer($buyerAccount, $email)
    {
        $customer = null;

        // 1. 优先使用邮箱查询（如果邮箱非空）
        if (!empty($email)) {
            $customer = Db::name('customer')
                ->where('email', $email)
                ->find();
        }

        // 2. 邮箱查询无结果时，使用买家账号查询
        if (!$customer && !empty($buyerAccount)) {
            $customer = Db::name('customer')
                ->where('cusname', $buyerAccount)
                ->find();
        }

        // 3. 如果客户存在，直接返回ID
        if ($customer) {
            return $customer['id'];
        }

        // 4. 客户不存在时创建新客户
        $data = [
            'cusname' => $buyerAccount,  // 客户名称 = 买家账号
            'email' => $email ?: '',      // 邮箱（可能为空）
            'create_time' => date('Y-m-d H:i:s'), // 当前时间
            'status' => 0,                // 默认客户状态
            'is_login' => 2,              // 默认未登录
            'login_status' => 1,          // 状态正常
            'role' => 'user',             // 默认普通用户
        ];

        // 插入客户并返回ID
        return Db::name('customer')->insertGetId($data);
    }
    private function getLocalProductId($sku,$batchNumber)
    {

        if (empty($sku)) {
            return [];
        }
        $sku = trim($sku,'"');
        $productId = Db::name('product')->where('sku', $sku)->value('id');
        if (!$productId) {
            return [];
        }
        if(!$batchNumber){
            return ['productid'=>$productId];
        }
        $inventory = Db::name('inventory')->where([
            ['productid', '=', $productId],
            ['inbound_batch', '=', $batchNumber], // ✅ 使用完整物流批次
            ['is_del', '=', 0]
        ])->order('create_time asc')->find();
        $inventory['productid'] = $productId;

        return $inventory;
    }
    private function getLocalWid($name)
    {
        if (empty($name)) {
            return 0;
        }
        $wid = Db::name('warehouse')->where('name', $name)->value('id');
        if (!$wid) {
            return 0;
        }

        return $wid;
    }
    private function getLocalCountry($name)
    {
        if (empty($name)) {
            return 0;
        }
        $wid = Db::name('region_country')->where('cname', $name)->value('id');
        if (!$wid) {
            return 0;
        }

        return $wid;
    }
    // 业务员ID映射
    private function getStaffId($staffName)
    {
        if (!$staffName) return 0;

        $staff = Db::name('operator')
            ->where('cname', $staffName)
            ->find();

        return $staff['id'] ?? 0;
    }

    // 币种处理
    private function processCurrency($currencyName, $excelRate)
    {

        $currencies = [
            'EUR' => ['id' => 1, 'rate' => $excelRate],
            'HKD' => ['id' => 6, 'rate' => $excelRate],
            'RUB' => ['id' => 22, 'rate' => $excelRate],
            'USD' => ['id' => 214, 'rate' => $excelRate],
            'CNY' => ['id' => 4, 'rate' => 1],
        ];

        $currency = $currencies[strtoupper($currencyName)] ?? ['id' => 4, 'rate' => 1];
        return [$currency['id'], $currency['rate']];
    }

    // Excel时间转Unix时间戳
    private function excelTimeToUnix($excelDate)
    {
        if (is_numeric($excelDate)) {
            return \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($excelDate);
        }
        return strtotime($excelDate);
    }

    // 处理订单明细
    private function processOrderItem($orderId, $item, $mapping, $currencyRate,$currencyId,$userId,$status)
    {
        $info = $this->getLocalProductId($item[$mapping['sku']],$item[$mapping['物流批次']]);
        $wid =$info['wid'] ?? 0;
        if($wid == 0){
            $wid = $this->getLocalWid($item[$mapping['仓库']]);
        }
        $itemData = [
            'order_id'   => $orderId,
            'user_id'    => $userId,
            'product_id' => $info['productid'] ?? 0,
            'arrival_date' => $info['arrival_date'] ?? null,
            'real_arrival_date' => $info['real_arrival_date'] ?? null,
            'warehouse_id' => $wid,
            'is_futures' => $info['is_futures'] ?? 0,
            'product_abbr' => $item[$mapping['商品简称']],
            'quantity'   => (int)$item[$mapping['销售数量']],
            'pending_quantity' => $status == 100? 0:(int)$item[$mapping['销售数量']], // 初始等于总数
            'original_price' => $this->convertCurrency(
                $currencyId,
                (float)$item[$mapping['售价']],
                $currencyRate
            ),
            'actual_price' => $this->convertCurrency(
                $currencyId,
                (float)$item[$mapping['售价']], // 根据实际业务调整
                $currencyRate
            ),
            'price_selected_currency' => $this->convertCurrency(
                $currencyId,
                (float)$item[$mapping['售价']],
                $currencyRate
            ),
            'transaction_currency_id' => Db::name('order')->where('id', $orderId)->value('currency'),
            'create_time' => date('Y-m-d H:i:s'),
            'exceptionstatus' => $wid == 0 ? 3:null,
        ];
      return $itemData;
    }

    // 货币转换
    private function convertCurrency($currencyId,$amount, $rate)
    {
        if($currencyId == 214 ){
            return $amount;
        }
        return round($amount * $rate, 2);
    }
}